<?php
namespace frontend\modules\cart\controllers;

use frontend\modules\base\controllers\BaseController;
use frontend\modules\cart\models\Cart;
use frontend\modules\goods\models\Goods;
use frontend\token\tokenCheck;
use Yii;
use yii\base\Exception;
use yii\web\Controller;

/**
 * 购物车信息接口
 *
 * Class CartController
 * @package frontend\modules\cart\controllers
 */
class CartController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public $enableCsrfValidation = false;

    /**
     * 获取用户购物车信息
     * @desc 验证令牌是否过期，是否正确通过
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return array data[].cart 购物车数据信息
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     */
    public function actionIndex()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $cartList =  Cart::find()
                    ->select('c.*,u.wx_name as refere_name,u.wx_images as refere_images')
                    ->from('cart as c')
                    ->leftJoin('user as u','c.refere_id  = u.qcode')
                    ->where(['c.user_id'=>$userinfo['id']])
                    ->asArray()
                    ->all();
                foreach($cartList as $key=>$val) {
                    $cartList[$key] = Goods::getCartByGoodsInfo($val);
                    if($val['is_check']==1){
                        $cartList[$key]['is_checkT']  = true;
                    }else{
                        $cartList[$key]['is_checkT']  = false;
                    }
                }
                $message = ['code'=>200,'message'=>'token验证成功','data'=>['openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token,'cart'=>$cartList]];
                return  json_encode($message);
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * 购物车选中，取消选中
     * @desc 传入id 、token、 rec_id
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string $data[rec_id] |购物车ID|yes|40位|
     * @param string $data[is_check] |是否选中|yes|0或1|
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCheck()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $postData = $this->post['data'];
                try{
                    $model = Cart::findOne($postData['rec_id']);
                    if($model ) {
                        $model->is_check = $postData['is_check'];
                        if($model->save()){
                            $message = ['code'=>200,'message'=>'选中成功','data'=>['openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token]];
                            return  json_encode($message);
                        }
                    }
                    throw new  Exception('此购物车选中失败！');
                }catch (Exception $e){
                    return $e->getMessage();
                }
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * 删除购物车
     * @desc 传入id 、token、 rec_id
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string $data[rec_id] |购物车ID|yes|40位|
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionDelcart()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $postData = $this->post['data'];
                try{
                    $model = Cart::findOne($postData['rec_id']);
                    if($model && $model->delete()) {
                        $message = ['code'=>200,'message'=>'删除成功','data'=>['openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token]];
                        return  json_encode($message);
                    }
                    throw new  Exception('此购物车删除失败！');
                }catch (Exception $e){
                    return $e->getMessage();
                }
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * 购物车增加数量
     * @desc 传入id 、token、 rec_id 、cart_number，购物车增减所需数据
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string $data[rec_id] |购物车ID|yes|40位|
     * @param int $data[add_cart_number] |商品增量|yes|整数|
     * @param string $data[type] |商品增减|yes|-:减少 +:增加|
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCartnum()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $postData = $this->post['data'];
                try{
                    if($this->ChangeCartnum($postData)==true) {
                        $message = ['code'=>200,'message'=>'成功添加'.$postData['type'].$postData['add_cart_number'].'个商品入购物完成','data'=>['openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token]];
                        return  json_encode($message);
                    }
                }catch (Exception $e){
                    return $e->getMessage();
                }
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * @param $postData
     * @return bool
     * @throws Exception
     */
    public function ChangeCartnum($postData)
    {
        $rec_id =  $postData['rec_id'];
        $type = $postData['type'];
        $model = Cart::findOne($rec_id);
        switch($type){
            case '+':
                $model->goods_number = $model->goods_number+$postData['add_cart_number'];
                break;
            case '-':
                $model->goods_number = $model->goods_number-$postData['add_cart_number'];
                break;
        }

        if($model->goods_number<=0) {
            throw new Exception('购物车数量不可小于或等于0！');
        }
        $model->cart_price = $model->goods_number*$model->shop_price;
        if($model->save()){
            return  true;
        }
        throw new Exception('购物车更新错误！');
    }

    /**
     * 添加购物车
     * @desc 传入id 、token、 goods_id 、cart_number，添加购物车所需数据
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string $data[goods_id] |商品ID|yes|40位|
     * @param string $data[refere_id] |推荐人ID|no|40位|
     * @param string $data[cart_number] |商品数量|yes|其他说明|
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionAddcart()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $postData = $this->post['data'];
                try{
                    $cart_id= $this->goodsToCart($postData);
                    if($cart_id) {
                        $message = ['code'=>200,'message'=>'成功添加入购物车','data'=>['cart_id'=>$cart_id,'openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token]];
                        return  json_encode($message);
                    }
                }catch (Exception $e){
                    return $e->getMessage();
                }
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * 添加如购物车
     *
     * @param $postData
     * @return bool
     * @throws Exception
     */
    public function goodsToCart($postData)
    {
        $goods_id  = $postData['goods_id'];
        $cart_number  = $postData['cart_number'];
        $user_id = \Yii::$app->UserInfo->userid;
        $refere_id = \Yii::$app->UserInfo->qcode;
        $ordersn = \Yii::$app->session->get('ordersn');

        if($refere_id){
            $cart = Cart::find()->where(['goods_id'=>$goods_id,'user_id'=>$user_id,'refere_id'=>$refere_id])->one();
            //判断是否购物车已经有添加
            if($cart) {
                $cart->goods_number += $cart_number;
                $cart->cart_price += $cart->shop_price*$cart_number;
                if($cart->save()){
                    return $cart->rec_id;
                }
            }
        } else{
            $cart = Cart::find()->where(['goods_id'=>$goods_id,'user_id'=>$user_id])->one();
            //判断是否购物车已经有添加
            if($cart) {
                $cart->goods_number += $cart_number;
                $cart->cart_price += $cart->shop_price*$cart_number;
                if($cart->save()){
                    return $cart->rec_id;
                }
            }
        }

        $goods = Goods::find()->where(['goods_id'=>$goods_id])->asArray()->one();
        if($goods){
            if($goods['goods_number']>=$cart_number){
                $cart = new Cart();
                $cart->user_id=$user_id;
                $cart->goods_id=$goods_id;
                $cart->goods_name=$goods['goods_name'];
                $cart->shop_price=$goods['shop_price'];
                $cart->market_price=$goods['market_price'];
                $cart->goods_image=$goods['goods_image'];
                $cart->thumb_img=$goods['thumb_img'];
                $cart->cart_price=$goods['shop_price']*$cart_number;
                $cart->goods_number=$cart_number;
                $cart->refere_id=$refere_id;
                $cart->re_ordersn=$ordersn;
                $cart->attr_cat_id=$goods['attr_cat_id'];
                $cart->is_gift=$goods['is_gift'];
                $cart->is_check=0;
                if($cart->save()){
                    return $cart->rec_id;
                }
                $message = ['code'=>500,'message'=>'添加购物车错误'];
                throw new Exception(json_encode($message));
            } else {
                $message = ['code'=>500,'message'=>'商品库存不足，请减量购买！'];
                throw new Exception(json_encode($message));
            }
        }
    }

    /**
     * 全选，取消全选
     * @desc  全选，取消全选
     *
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string data[is_checked_all] |是否选中全部|yes|0或1 0 全部取消  1 全部选中|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionSetallchecked()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if($userinfo){
                $postData = $this->post['data'];
                $beginTransaction = Yii::$app->db->beginTransaction();
                $userid = Yii::$app->UserInfo->userid;
                try {
                    if ($postData['is_checked_all']) {
                        Cart::updateAll(
                            ['is_check' => 1], "user_id='$userid'"
                        );
                    } else {
                        Cart::updateAll(
                            ['is_check' => 0], "user_id='$userid'"
                        );
                    }
                    $beginTransaction->commit();
                }catch (Exception $e){
                    $beginTransaction->rollBack();
                    $message = ['code'=>500,'message'=>$e->getMessage(),'data'=>[]];
                    return  json_encode($message);
                }
                $message = ['code'=>200,'message'=>'选中成功','data'=>[]];
                return  json_encode($message);
            }
        }else{
            return $userinfo;
        }
    }
}
